package club.calong.sanniu.controller;

import club.calong.sanniu.http.request.UserRequest;
import club.calong.sanniu.http.response.MessageResponseData;
import club.calong.sanniu.http.response.Response;
import club.calong.sanniu.service.AdminService;
import club.calong.sanniu.util.CacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/admin")
public class AdminController {

    AdminService service;

    @Autowired
    public AdminController(AdminService service) {
        this.service = service;
    }

    @PostMapping
    @PreAuthorize("hasAnyAuthority('admin:update')")
    public Response create (@RequestBody UserRequest user) {

        return service.create(user) ?
                new Response(Response.SUCCESS, Response.Message.INSERT_OK, user) :
                new Response(Response.FAILURE, Response.Message.INSERT_ERROR, null);
    }

    @PutMapping
    @PreAuthorize("hasAnyAuthority('admin:update')")
    public Response update (@RequestBody UserRequest user) {

        return service.update(user) ?
                new Response(Response.SUCCESS, Response.Message.UPDATE_OK, user) :
                new Response(Response.FAILURE, Response.Message.UPDATE_ERROR, null);
    }

    @DeleteMapping("{id}")
    @PreAuthorize("hasAnyAuthority('admin:update')")
    public Response delete (@PathVariable("id") Integer id) {

        return service.delete(id) ?
                new Response(Response.SUCCESS, Response.Message.DELETE_OK, null) :
                new Response(Response.FAILURE, Response.Message.DELETE_ERROR, null);
    }

    @GetMapping("info")
    public Response info (HttpServletRequest request) {

        return new Response(Response.SUCCESS, service.info(request.getHeader("X-Token")));
    }

    @GetMapping("list/{page}/{size}")
    @PreAuthorize("hasAnyAuthority('admin:select')")
    public Response page (@PathVariable("page") Integer page, @PathVariable("size") Integer size) {

        return new Response(Response.SUCCESS, null, service.page(page, size, false));
    }

    @GetMapping("user/{page}/{size}")
    @PreAuthorize("hasAnyAuthority('user:select')")
    public Response user (@PathVariable("page") Integer page, @PathVariable("size") Integer size) {

        return new Response(Response.SUCCESS, null, service.page(page, size, true));
    }
}
